package org.goldenport.g3.adapters

import scala.xml.{XML, Elem}
import java.io._
import java.net.{URL, URI}
import org.goldenport.g3._
import org.goldenport.g3.messages._
import org.goldenport.g3.messages.file._
import org.goldenport.g3.events.file._
import com.asamioffice.goldenport.io.{UFile, UURL, UIO}
import org.goldenport.entity.GEntity
import org.goldenport.entity.content.GContent

/**
 * @since   Sep. 20, 2010
 * @version Sep. 24, 2010
 * @author  ASAMI, Tomoharu
 */
class HttpAdapter(val uri: URI) extends G3Adapter with ActivityActionable {
  val driver = new HttpDriver(uri)

  def create_Activity(ctx: G3AgentContext) = driver.createDriverActivity(ctx)
}

class HttpDriver(val uri: URI, val encoding: String = "utf-8", val mime: Option[String] = None) extends G3Driver {
  override def driver_Activity(ctx: G3AgentContext): PartialFunction[AnyRef, AnyRef] = {
    case cmd: G3Command => execute(cmd, ctx)
    case blob: Blob => execute(Post("", blob), ctx)
    case string: String => execute(Post("", string), ctx)
    case gcontent: GContent => execute(Post("", gcontent), ctx)
    case gentity: GEntity => execute(Post(gentity.name, gentity), ctx)
  }

  protected def new_Agent(cmd: G3Command, ctx: G3AgentContext): HttpDriverAgent = {
    new HttpDriverAgent(uri, encoding, mime, ctx)
  }
}

class HttpDriverAgent(uri: URI, val encoding: String, val mime: Option[String], context: G3AgentContext) extends G3DriverAgent(uri.toString, context) {
  val gDataSource = context.getDataSource(uri)

/*
  agent {
    case cmd: http.POST => create_file(cmd)
    case cmd: http.GET => read_file(cmd)
    case cmd: http.PUT => write_file(cmd)
    case cmd: http.DELETE => remove_file(cmd)
  }
*/

  //
  def get(get: Get): G3Event = {
    // XXX reconstitute GEntity
    val hget = http.GET(get.uri)
    context.httpGet(hget)
  }

  def post(post: Post): G3Event = {
    error("XXX post")
  }

  def put(put: Put): G3Event = {
    error("XXX put")
  }

  def delete(delete: Delete): G3Event = {
    error("XXX delete")
  }

  def mkcol(mkcol: Mkcol): G3Event = {
    error("XXX mkcol")
  }
}
